<script lang="ts" setup>
const emit = defineEmits<{
  onRefresh: []
}>()
const loading = ref(false)
const onRefresh = async () => {
  const tips = showLoadingToast('加载中...')
  emit('onRefresh')
  await new Promise((resolve) => setTimeout(resolve, 600))
  loading.value = false
  tips.close()
}

// vant下拉刷新与局部滚动冲突解决方案
const disabled = ref(false)
// 从touchstart的e.target开始向上查找滚动父级，而不是vant的从van-pull-refresh根节点开始向上查找滚动父级
const onTouchstart = (e: TouchEvent) => {
  const parent = (e.target as HTMLElement).closest<HTMLElement>('[data-cache-scroll-top]')
  if (parent) {
    // Math.max处理ios中scrollTop为负数的情况
    disabled.value = Math.max(Number(parent.dataset.cacheScrollTop), 0) > 0
  }
}
const onTouchend = () => disabled.value = false
// 解决van-pull-refresh的先上拉产生滚动后再下拉，导致未到顶部就提前触发下拉刷新bug
const onScroll = () => disabled.value = true
</script>

<template>
  <Resize class="PullRefresh" v-slot="{ h }" @touchstart.capture="onTouchstart" @touchend="onTouchend"
    @touchcancel="onTouchend" @scroll.capture="onScroll">
    <van-pull-refresh :disabled v-model="loading" @refresh="onRefresh">
      <div class="page" :style="{ minHeight: `${h - 0.5}px`, '--pull-refresh-height': `${h - 0.5}px` }">
        <slot />
      </div>
    </van-pull-refresh>
  </Resize>
</template>

<style lang="scss" scoped>
.PullRefresh {
  overflow-y: auto;
}
</style>
